//
//  InputVerifyViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/9/20.
//

import UIKit
import RxCocoa

enum InputViewType {
    case regist
    case forgetPassword
    case closeAccount
}

class InputVerifyViewController: BaseViewController {
    var titleLab: UILabel!
    var phoneLab: UILabel!
    var codeView: MHVerifyCodeView!
    var resentBtn: UIButton!
    var timer: Timer!
    var timeCount: NSInteger = 60
    var msgTipLab: UILabel! //提示语
    var cacheCode: String = "" //记录输入的code
    private var dataModel = UserInfoObj()
    
    ///pageType 0：注册 1：忘记密码 2:注销帐户
    var pageType: InputViewType = .regist
    var phoneStr: String = "" //传过来的phone
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .white
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.dataModel.phone = self.phoneStr
        
        titleLab = UILabel()
        titleLab.textColor = Theme.mainColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 26)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        titleLab.text = MMLocalizedString("verify_enter_code", comment: "请输入验证码")
        self.view.addSubview(titleLab)
        
        codeView = MHVerifyCodeView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth - 60, height: 50))
        codeView.font = UIFont.init(name: Theme.PingFangSCMedium, size: 20)!
        codeView.verifyCount = 6
        codeView.spacing = 8
        codeView.completeHandler = {[weak self] code in
            self?.cacheCode = code
            if self?.pageType != .closeAccount {
                self?.fetchVerifyCode(code: code)
            }
        }
        self.view.addSubview(codeView)
        
        resentBtn = UIButton()
        resentBtn.setup_titleLabel(text: MMLocalizedString("verify_resend_code", comment: "重新获取验证码"))
        resentBtn.setup_titleColor(color: Theme.titleLabColor)
        resentBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        resentBtn.setBackgroundImage(UIImage.init(color: Theme.whiteColor), for: .normal)
        resentBtn.setBackgroundImage(UIImage.init(color: Theme.eColor), for: .highlighted)
        resentBtn.addTarget(self, action: #selector(resentBtnAction), for: .touchUpInside)
        view.addSubview(resentBtn)
        
        msgTipLab = UILabel()
        msgTipLab.textColor = Theme.redColor
        msgTipLab.backgroundColor = UIColor.clear
        msgTipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        msgTipLab.numberOfLines = 1
        msgTipLab.lineBreakMode = .byTruncatingTail
        msgTipLab.textAlignment = .center
        view.addSubview(msgTipLab)
        
        
        if self.pageType == .closeAccount {
            titleLab.text = MMLocalizedString("logout_verification", comment: "注销账号验证")
            phoneLab = UILabel(frame: CGRect(x: 14, y: titleLab.frame.maxY , width: kScreenWidth - 24, height: 30))
            phoneLab.textColor = Theme.titleLabColor
            phoneLab.font = UIFont(name: Theme.PingFangSCRegular, size: 14)
            phoneLab.textAlignment = .center
            phoneLab.numberOfLines = 0
            phoneLab.text = MMLocalizedString("verification_message", comment: "已发送验证短信至手机号") +  XTManageCenter.getAsterisk(text: self.phoneStr)
            self.view.addSubview(phoneLab)
            self.createBottomBtnView()
        }
        
        self.addSnpLayout()
        
    }
    
    ///确定注销按钮
    func createBottomBtnView() {
        let tempH: CGFloat = IphoneXMarginBottom + 54
        let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - tempH, width: kScreenWidth, height: tempH))
        bgView.backgroundColor = .clear
        self.view.addSubview(bgView)
        
        let cancelBtn = UIButton(frame: CGRect(x: 14, y: 4, width: kScreenWidth - 28, height: 46))
        cancelBtn.backgroundColor = Theme.mainColor
        cancelBtn.layer.cornerRadius = 8
        cancelBtn.layer.masksToBounds = true
        cancelBtn.setTitleColor(.white, for: .normal)
        cancelBtn.setTitle(MMLocalizedString("definitive_cancellation", comment: "确定注销"), for: .normal)
        cancelBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 16)
        cancelBtn.addTarget(self, action: #selector(cancelBtnAntion), for: .touchUpInside)
        bgView.addSubview(cancelBtn)
    }
    
    deinit {
        if self.timer != nil {
            self.timer.invalidate()
            self.timer = nil
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //短信发送成功,倒计时开始
        self.handleTimer()
        self.view.makeToast(message: MMLocalizedString("verify_has_resend_code", comment: ""))
    }
    
    private func addSnpLayout(){
        titleLab.snp.makeConstraints { make in
            make.top.equalTo(NavBarHight + 88)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        
        if self.pageType == .closeAccount{
            self.phoneLab.snp.makeConstraints { make in
                make.top.equalTo(titleLab.snp.bottom).offset(5)
                make.left.equalTo(14)
                make.right.equalTo(-14)
                
            }
        }
        
        
        codeView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalTo(titleLab.snp.bottom).offset(40)
            make.width.equalTo(kScreenWidth-60)
            make.height.equalTo(50)
        }
        
        msgTipLab.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(codeView.snp.bottom).offset(46)
        }
        
        resentBtn.titleLabel?.sizeToFit()
        let tempW = resentBtn.titleLabel?.frame.size.width ?? 0
        resentBtn.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(msgTipLab.snp.bottom).offset(46)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(tempW + 20)
        }
    }
    
    ///重新获取
    @objc func resentBtnAction(){
        self.msgTipLab.text = ""
        self.codeView.borderColor = Theme.tfBorderColor.cgColor
        self.dataModel.captchaCode = ""
        self.updateViewConstraints()
        self.resentBtn.isUserInteractionEnabled = false
        self.fetchGetSMSCode()
    }
    
    //确定注销
    @objc func cancelBtnAntion(){
        if self.cacheCode.count < 6 {
            return
        }
        XTAlertView.showAlertView(title: MMLocalizedString("add_tip", comment: "提示"),
                                  message: MMLocalizedString("close_your_account", comment: "注销操作无法撤回，确定注销账号吗？"),
                                  cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                  otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")])
        { alertView, buttonIndex in
            if buttonIndex == 1 {
                self.resignAccount()
            }
        }
    }
    
    ///注销账号
    private func resignAccount() {
        var param = NSMutableDictionary() as! [String: String]
        param["phone"] = self.phoneStr
        param["sendType"] = "3"
        param["code"] = self.cacheCode
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.logoutAccount(param: param), objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                self.view.makeToast(message: MMLocalizedString("resign_acc_success", comment: "注销成功"))
                self.perform(#selector(self.jumpHomePage), afterDelay: 1.4)
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///注销成功跳转到首页，再跳登录页
    @objc func jumpHomePage() {
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        self.navigationController?.popToRootViewController(animated: false)
        tabbarVC.selectedIndex = 0
        XTManageCenter.shared.jumpToLoginView()
    }
    
    ///获取验证码 sendType类型 1注册,2找回密码，3注销
    private func fetchGetSMSCode(){
        self.view.showLoadingHUDText()
        guard self.dataModel.phone != "" else {
            self.view.makeToast(message: MMLocalizedString("forget_please_enter_real_phone", comment: "请输入正确的手机号码"))
            return
        }
        
        let areaCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        var type = "0"
        switch self.pageType {
            case .closeAccount:
                type = "3"
            case .regist:
                type = "1"
            default:
                type = "2"
        }
        let param: [String: String] = ["mobileAreaCode": areaCode,
                                       "phone": self.dataModel.phone,
                                       "sendType": type]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.captchaGetCode(param: param), objectType: SMSCodeModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? SMSCodeModel
            guard let code = resultObj?.code, code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                self.resentBtn.isUserInteractionEnabled = true
                return
            }
            self.view.makeToast(message: MMLocalizedString("verify_has_resend_code", comment: "已重新发送验证码"))
            self.handleTimer()
        } error: { err in
            self.resentBtn.isUserInteractionEnabled = true
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///定时器启动
    func handleTimer() {
        if self.timer != nil {
            timer.invalidate()
            timer = nil
        }
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCountDown), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .commonModes)
    }
    
    ///倒计时
    @objc func timerCountDown(){
        if self.timeCount > 0 {
            self.timeCount = self.timeCount - 1
            let str = String(format: "%@ (%ds)", MMLocalizedString("verify_resend_code", comment: "重新获取验证码"), self.timeCount)
            resentBtn.setup_titleLabel(text: str)
            resentBtn.setup_titleColor(color: Theme.placeholderColor)
            resentBtn.isUserInteractionEnabled = false
        }else{
            self.timer.invalidate()
            self.timer = nil
            resentBtn.setup_titleColor(color: Theme.titleLabColor)
            resentBtn.setup_titleLabel(text: MMLocalizedString("verify_resend_code", comment: "重新获取验证码"))
            resentBtn.isUserInteractionEnabled = true
        }
    }
    
    
    ///请求校验填写的code  sendType 类型 1注册,2找回密码，3注销
    private func fetchVerifyCode(code: String){
        self.view.endEditing(true)
        self.view.resignFirstResponder()
        
        let areaCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        var type: String = "2"
        switch self.pageType {
            case .closeAccount:
                type = "3"
            case .regist:
                type = "1"
            default:
                type = "2"
        }
        self.view.showLoadingHUDText()
        let param: [String: String] = ["mobileAreaCode": areaCode,
                                       "phone": self.dataModel.phone,
                                       "code": code,
                                       "sendType": type]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.captchaVerify(param: param), objectType: SMSCodeModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? SMSCodeModel
            if resultObj?.code == "10" {
                //验证码错误
                self.msgTipLab.text = MMLocalizedString("verify_code_expire", comment: "验证码错误或已过期")
                self.codeView.warnBorderAnimate = true
                self.updateViewConstraints()
                return
            }
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            self.dataModel.captchaCode = code
            self.jumpToInfo()
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///校验code成功，填写信息
    func jumpToInfo(){
        if self.pageType == .regist {
            let vc = AddUserInfoViewController()
            vc.dataModel = self.dataModel
            self.navigationController?.pushViewController(vc, animated: true)
        }else if pageType == .forgetPassword {
            //去重置密码
            let vc = ResetPasswordViewController()
            vc.phoneStr = self.phoneStr
            vc.captCode = self.dataModel.captchaCode
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}
